package cn.clouds234.json.jackson;

import cn.clouds234.entity.Student;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Arrays;
import java.util.List;

/**
 * @author wyf
 * @date 2025/1/21 21:08
 */
public class JacksonDemo {
    private static final  ObjectMapper objectMapper = new ObjectMapper();
    public static void main(String[] args) throws JsonProcessingException {
//       objToJson();
//        jsonToObj();
//        listToJson();
//        jsonToList();
        jsonToJsonNode();
    }

    public static void jsonToObj() throws JsonProcessingException {
        String s = "{\"name\":\"tom\",\"age\":12,\"sex\":\"man\"}";
        Student student = objectMapper.readValue(s, Student.class);
        System.out.println(student.getName());
    }
    public static void objToJson() throws JsonProcessingException {
        Student student = new Student();
        student.setAge(12);
        student.setName("tom");
        student.setSex("man");
        System.out.println(objectMapper.writeValueAsString(student));
    }
    public static void listToJson() throws JsonProcessingException {
        List<String> ss = Arrays.asList("a", "b", "c", "d");
        System.out.println(objectMapper.writeValueAsString(ss));

    }
    public static void jsonToList() throws JsonProcessingException {
        String l = "[\"a\",\"b\",\"c\",\"d\"]";
        List<String> s = objectMapper.readValue(l, new TypeReference<List<String>>() {});
        for (String s1 : s) {
            System.out.println(s1);
        }
    }

    public static void jsonToJsonNode() throws JsonProcessingException {
        String s = "{\"name\":\"tom\",\"info\": {\"age\":12,\"sex\":\"man\"}}";
        JsonNode jsonNode = objectMapper.readTree(s);
        JsonNode name = jsonNode.get("name");
        System.out.println(name.asText());
        JsonNode info = jsonNode.get("info");
        Student student = objectMapper.treeToValue(info, Student.class);
        JsonNode age = info.get("age");
        System.out.println(age.asInt());
    }
}
